import java.util.HashMap;
import java.util.Map;

import com.aliyun.odps.udf.UDF;
import com.aliyun.odps.utils.StringUtils;
import com.google.gson.Gson;

public class GoodsSamePart extends UDF {

	
	
	
	/*
	 * public static void main(String[] args) {
	 * 
	 * String brand = "Ecco Bella Vitamin E Lip Smoother"; String aUrl =
	 * "https://www.ewg.org/skindeep/product/721979/Ecco_Bella_Vitamin_E_Lip_Smoother%2C_Sugar_Plum_%282017_formulation%29/";
	 * String aTitle = " Spice"; String bUrl =
	 * "https://www.ewg.org/skindeep/product/721978/Ecco_Bella_Vitamin_E_Lip_Smoother%2C_Spice/";
	 * String bTitle = "A+D Original Ointment"; System.out.println(evaluate(brand,
	 * aUrl, aTitle, bUrl, bTitle));
	 * 
	 * }
	 */
	 
	 
	 

	/**
	 * 查找出相似部分
	 * 
	 * @param brand
	 * @param aUrl
	 * @param aTitle
	 * @param bUrl
	 * @param bTitle
	 * @return
	 */
	public String evaluate(String brand, String aUrl, String aTitle, String bUrl, String bTitle) {
		try {
			Map<String, String> map = new HashMap<String, String>();
			Gson gson = new Gson();
			// 同一商品不做比较
			if (StringUtils.equals(aTitle,bTitle)) {
				return null;
			}
			
			//将两个title比较，短的在前面，长的在后面。方便进行去重，因为A和B比，B也会和A比     url对应存入map
			String minTitle = null;
			String maxTitle = null;
			if(aTitle.length() > bTitle.length()) {
				//大于
				minTitle = bTitle;
				maxTitle = aTitle;
			}else if(aTitle.length() < bTitle.length()) {
				//小于
				minTitle = aTitle;
				maxTitle = bTitle;
			}else if(aTitle.length() == bTitle.length()) {
				//=于
				if(aTitle.hashCode() > bTitle.hashCode()) {
					minTitle = bTitle;
					maxTitle = aTitle;
				}else {
					minTitle = aTitle;
					maxTitle = bTitle;
				}
			}
			
			//String allTitle = aTitle.length() > bTitle.length() ? bTitle+"@@"+aTitle : aTitle+"@@"+bTitle;
			//String[] split = allTitle.split("@@");
			map.put("minTitle", minTitle);
			map.put("maxTitle", maxTitle);
			//将url对应
			if(aTitle.equals(minTitle)) {
				map.put("minUrl", aUrl);
				map.put("maxUrl", bUrl);
			}else {
				map.put("minUrl", bUrl);
				map.put("maxUrl", aUrl);
			}
			
			
			// 替换title中的brand
			aTitle = aTitle.replace(brand, "");
			bTitle = bTitle.replace(brand, "");
			System.out.println(aTitle + "----------" + bTitle);
			// 不同商品将title转成大写，除去空格，切成数组
			String[] aArr = aTitle.toUpperCase().replace(" ", "").split("");
			String[] bArr = bTitle.toUpperCase().replace(" ", "").split("");
			// 获取短数组的长度
			int minArrLength = aArr.length > bArr.length ? bArr.length : aArr.length;
			StringBuffer sb = new StringBuffer();
			// 循环
			for (int i = 0; i < minArrLength; i++) {
				if (!StringUtils.equals(aArr[i], bArr[i])) {
					break;
				}
				sb.append(aArr[i]);
			}

			// return sb.toString();
			System.out.println(sb.toString());
			//相似部分
			map.put("comePart", sb.toString());
			System.out.println(gson.toJson(map));
			// 返回
			return gson.toJson(map);
		} catch (Exception e) {
			return "数据异常---"+aUrl+"---"+bUrl;
		}
	}
}
